% This file generates .csv files with data for IS plots together with confidence intervals

clear;clc;
load P00Data;
load Market;
load ClarkMcCrackenCriticalValues;

Names=cell(4,2);
Names{1,1}='Results_Simple_M'; Names{2,1}='Results_Simple_Q'; Names{3,1}='Results_Simple_ADec'; Names{4,1}='Results_Simple_AJun';
Names{1,2}='Results_Log_M'; Names{2,2}='Results_Log_Q'; Names{3,2}='Results_Log_ADec'; Names{4,2}='Results_Log_AJun';

OutFile=cell(4,2);
OutFile{1,1}='DataForPlotIS_Simple_M.csv'; OutFile{2,1}='DataForPlotIS_Simple_Q.csv'; OutFile{3,1}='DataForPlotIS_Simple_ADec.csv'; OutFile{4,1}='DataForPlotIS_Simple_AJun.csv';
OutFile{1,2}='DataForPlotIS_Log_M.csv'; OutFile{2,2}='DataForPlotIS_Log_Q.csv'; OutFile{3,2}='DataForPlotIS_Log_ADec.csv'; OutFile{4,2}='DataForPlotIS_Log_AJun.csv';

for freq = 1:4
    if freq==1
        TSVAR = yyyymm; LengthT = TM;
    elseif freq==2
        TSVAR = yyyyq; LengthT = TQ;
    else
        TSVAR = yyyy; LengthT = TA;
    end
    for ct = 1:2
        load('ResultsFile',Names{freq,ct}); Results = eval(Names{freq,ct});
        ForGraph = NaN(46,3,LengthT);
        for i = 1:46
            if freq==1 && ~strcmp(VARS(i).Freq,'Monthly')
                continue;
            elseif freq==2 && (strcmp(VARS(i).Freq,'Annual') || strcmp(VARS(i).Freq,'Semiannual'))
                continue;
            end
            SampleBeg = find(TSVAR==Results(i).SampleBeg) + 1; SampleEnd = find(TSVAR==Results(i).SampleEnd);
            e2diff = Results(i).ISStats.ErrUnc.^2 - Results(i).ISStats.ErrMdl.^2; e2diff = e2diff(SampleBeg:SampleEnd);
            TT = length(e2diff);
            DD = NaN(TT,1);
            for t = 1:TT
                ee = e2diff(1:t);
                eesum = sum(ee);
                DD(t) = eesum;
            end
            ForGraph(i,SampleBeg:SampleEnd) = DD;
        end
        
        fp = fopen(OutFile{freq,ct},'w');        
        fprintf(fp,'Date');
        for i = 1:46
            if freq==1 && ~strcmp(VARS(i).Freq,'Monthly')
                continue;
            elseif freq==2 && (strcmp(VARS(i).Freq,'Annual') || strcmp(VARS(i).Freq,'Semiannual'))
                continue;
            end
            fprintf(fp,',%s',VARS(i).Name);
        end
        fprintf(fp,'\n');
        for t = 1:LengthT
            fprintf(fp,'%d',TSVAR(t));
            for i = 1:46
                if freq==1 && ~strcmp(VARS(i).Freq,'Monthly')
                    continue;
                elseif freq==2 && (strcmp(VARS(i).Freq,'Annual') || strcmp(VARS(i).Freq,'Semiannual'))
                    continue;
                end
                fprintf(fp,',%.6f',ForGraph(i,t));
            end
            fprintf(fp,'\n');
        end
        fclose(fp);
    end
end